#include "net_interface.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 网络接口全局变量
static uint32_t my_ip = 0;
static packet_receive_callback_t receive_callback = NULL;

// 初始化网络接口
int net_interface_init(uint32_t ip) {
    my_ip = ip;
    receive_callback = NULL;
    printf("Network interface initialized with IP: %d.%d.%d.%d\n", 
           (my_ip >> 24) & 0xFF, (my_ip >> 16) & 0xFF, 
           (my_ip >> 8) & 0xFF, my_ip & 0xFF);
    return 0;
}

// 清理网络接口
void net_interface_cleanup(void) {
    // 在实际实现中，这里应该释放网络资源
    printf("Network interface cleaned up\n");
}

// 发送数据包
int net_interface_send(uint32_t dest_ip, uint8_t protocol, const void *data, size_t data_len) {
    // 在实际实现中，这里应该调用底层网络栈发送数据包
    printf("Sending packet from %d.%d.%d.%d to %d.%d.%d.%d, protocol: %d, length: %u\n",
           (my_ip >> 24) & 0xFF, (my_ip >> 16) & 0xFF, (my_ip >> 8) & 0xFF, my_ip & 0xFF,
           (dest_ip >> 24) & 0xFF, (dest_ip >> 16) & 0xFF, (dest_ip >> 8) & 0xFF, dest_ip & 0xFF,
           protocol, (unsigned int)data_len);
    
    // 模拟发送成功
    return 0;
}

// 广播数据包
int net_interface_broadcast(uint8_t protocol, const void *data, size_t data_len) {
    // 在实际实现中，这里应该调用底层网络栈发送广播包
    printf("Broadcasting packet from %d.%d.%d.%d, protocol: %d, length: %u\n",
           (my_ip >> 24) & 0xFF, (my_ip >> 16) & 0xFF, (my_ip >> 8) & 0xFF, my_ip & 0xFF,
           protocol, (unsigned int)data_len);
    
    // 模拟发送成功
    return 0;
}

// 设置数据包接收回调函数
void net_interface_set_receive_callback(packet_receive_callback_t callback) {
    receive_callback = callback;
}

// 获取本地IP地址
uint32_t net_interface_get_my_ip(void) {
    return my_ip;
}

// 模拟网络接收（用于测试）
int net_interface_simulate_receive(uint32_t src_ip, uint8_t protocol, const void *data, size_t data_len) {
    if (receive_callback != NULL) {
        return receive_callback(src_ip, protocol, data, data_len);
    }
    printf("No receive callback registered, packet from %d.%d.%d.%d dropped\n",
           (src_ip >> 24) & 0xFF, (src_ip >> 16) & 0xFF, (src_ip >> 8) & 0xFF, src_ip & 0xFF);
    return -1;
}